package echat.future.cn.echat.my.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import echat.future.cn.echat.my.bean.BaseVo;
import echat.future.cn.echat.my.http.RetrofitClient;
import echat.future.cn.echat.my.weight.ProgrossDialog;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;
import retrofit2.Retrofit;

public class HttpUtilsRequst<T> {
    private  ProgrossDialog progrossDialog;
    public static Retrofit retrofitClient;
    public static void init(Context context){
        retrofitClient = new RetrofitClient(context,"https://eliao-tv.com/").getRetrofit();
    }

    /**
     * 相应成功的接口
     */
    private OnRequstSuccessListener mOnRequstSuccessListener;

    /**
     * 相应失败的接口
     */
    private OnRequstFaileListener mOnRequstFaileListener;

    /**
     * 上下文内容
     */
    private Context mContext;

    /**
     * 可观察者
     */
    private Observable<BaseVo<T>> mObservable;

    public HttpUtilsRequst(Context context,Observable observable){
        mContext = context;
        progrossDialog = new ProgrossDialog(context);
        this.mObservable = observable;
        isShowPro = true;
    }

    private boolean isShowPro;
    private boolean isShowError;
    public HttpUtilsRequst(Context context,Observable observable,boolean isShowPro){
        this.isShowPro = isShowPro;
        mContext = context;
        progrossDialog = new ProgrossDialog(context);
        this.mObservable = observable;
    }

    public HttpUtilsRequst setmOnRequstSuccessListener(OnRequstSuccessListener mOnRequstSuccessListener) {
        this.mOnRequstSuccessListener = mOnRequstSuccessListener;
        return this;
    }

    public HttpUtilsRequst setmOnRequstFaileListener(OnRequstFaileListener mOnRequstFaileListener) {
        this.mOnRequstFaileListener = mOnRequstFaileListener;
        return this;
    }

    @SuppressLint("CheckResult")
    public void start(){
        mObservable.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<BaseVo<T>>() {
            @Override
            public void onSubscribe(Disposable d) {
                if(((Activity)mContext).isDestroyed() || ((Activity)mContext).isFinishing()){
                    d.dispose();
                    return;
                }
                if(progrossDialog != null){
                    if(!progrossDialog.isShowing() && isShowPro) {
                        progrossDialog.show();
                    }
                }
            }

            @Override
            public void onNext(BaseVo<T> tBaseVo) {
                Log.e("okhttp",new Gson().toJson(tBaseVo));
                if(tBaseVo.getCode() == 1){
                    //正常
                    if(null != mOnRequstSuccessListener){
                        mOnRequstSuccessListener.onSuccss(tBaseVo.getData());
                    }
                }else{
                    if(tBaseVo.getCode() == -9001||tBaseVo.getCode()==-9002||tBaseVo.getCode()==-9003){
                        ToastUtils.toastMsg(mContext, tBaseVo.getMsg());
                        RouterHelper.toInvalidActivity(mContext);
                        return;
                    }
                    if(mOnRequstFaileListener != null) {
                        mOnRequstFaileListener.onFaile(tBaseVo.getCode(), tBaseVo.getMsg());
                    }else{
                        try {
                            ToastUtils.toastMsg(mContext, tBaseVo.getMsg());
                        }catch (Exception e){}
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                Log.e("okhttp",e.toString());
                if (e instanceof HttpException) {
                    /*网络异常*/
                    if(((HttpException) e).code() == 404){
                        erroTost(404,"找不到网络");
                    }else if(((HttpException) e).code() > 500){
                        erroTost(500,"服务器异常");
                    }else {
                        erroTost(500,"系统异常");
                    }
                } if (e instanceof ConnectException || e instanceof SocketTimeoutException) {
                    /*链接异常*/
                    erroTost(400,"网络链接异常");
                } else if (e instanceof JSONException || e instanceof ParseException) {
                    /*fastjson解析异常*/
                    erroTost(400,"数据解析错误");
                } else if (e instanceof UnknownHostException) {
                    /*无法解析该域名异常*/
                    erroTost(404,"找不到域名");
                }else{
                    erroTost(404,e.getMessage());
                }

                if(null != progrossDialog) {
                    progrossDialog.dismiss();
                }
            }

            @Override
            public void onComplete() {
                if(((Activity)mContext).isDestroyed() || ((Activity)mContext).isFinishing()){
                    return;
                }
                if(null != progrossDialog) {
                    progrossDialog.dismiss();
                }
            }
        });

    }

    public void erroTost(int code,String msg){
        if(mOnRequstFaileListener != null){
            mOnRequstFaileListener.onFaile(code,msg);
        }else{
            ToastUtils.toastMsg(mContext,msg);
        }
    }

    public interface OnRequstSuccessListener<T>{
        void onSuccss(T t);
    }
    public interface OnRequstFaileListener{
        void onFaile(int code, String msg);
    }
}
